package com.backend.mzyf.service.impl;

import com.backend.mzyf.Utils.MD5;
import com.backend.mzyf.dao.SysPermissionCustomMapper;
import com.backend.mzyf.dao.SysUserExampleMapper;
import com.backend.mzyf.entity.ActiveUser;
import com.backend.mzyf.entity.SysPermission;
import com.backend.mzyf.entity.SysUser;
import com.backend.mzyf.exception.CustomException;
import com.backend.mzyf.service.SysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("SysService")
public class SysServiceImpl<T> implements SysService {

    @Autowired
    private SysUserExampleMapper sysUserExampleMapper;

    @Autowired
    private SysPermissionCustomMapper sysPermissionCustomMapper;

    public ActiveUser authenticat(String usercode, String password) throws Exception {

        SysUser user = this.findSysUserByUsercode(usercode);

        if (user == null){
            throw new CustomException("用户名或者密码错误!");
        }

        String userId = user.getId();

        String passwordDb = user.getPassword();

        String passwordMd5 = new MD5().MD5(password);

        if (!passwordDb.equals(passwordMd5)){
            throw new CustomException("用户名或者密码错误");
        }

        List<SysPermission> menu = this.findMenuByUserId(userId);

        List<SysPermission> permissions = this.findPermissionByUserId(userId);

        ActiveUser activeUser = new ActiveUser();

        activeUser.setMenu(menu);
        activeUser.setPermissions(permissions);


        activeUser.setUsercode(user.getUsercode());
        activeUser.setUsername(user.getUsername());
        activeUser.setUserId(user.getId());


        return activeUser;
    }

    public SysUser findSysUserByUsercode(String usercode) throws Exception {
        return this.sysUserExampleMapper.selectByUserCode(usercode);
    }

    public List<SysPermission> findPermissionByUserId(String userId) throws Exception {
        return sysPermissionCustomMapper.findPermissionListByUserId(userId);
    }

    public List<SysPermission> findMenuByUserId(String userId) throws Exception {
        return sysPermissionCustomMapper.findMenuListByUserId(userId);
    }

}
